package team.yidong.fenda.wx.Service.Impl;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import team.yidong.fenda.entity.Answer;
import team.yidong.fenda.entity.Master;
import team.yidong.fenda.entity.MasterScore;
import team.yidong.fenda.entity.SysUser;
import team.yidong.fenda.repository.MasterRepository;
import team.yidong.fenda.repository.MasterScoreRepository;
import team.yidong.fenda.repository.SysUserRepository;
import team.yidong.fenda.wx.Service.WxMasterService;

import javax.persistence.criteria.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by xuanlong on 2017/10/15.
 */
@Service
public class WxMasterServiceImpl implements WxMasterService {
    @Autowired
    MasterRepository masterRepository;
    @Autowired
    MasterScoreRepository masterScoreRepository;
    @Autowired
    SysUserRepository sysUserRepository;

    @Override
    public JSONArray findMaster(Integer id) {
        List<Master> masterList = masterRepository.findMaster(id);
        JsonConfig config = new JsonConfig();
        config.setExcludes(new String[]{"hospitalPermissionSet", "master", "hospitalImgSet", "hospitalFieldList", "userSet", "masterList", "answer", "praiseUserSet", "answerList", "question", "masterScoreAnswer", "answerImgSet", "hospital", " masterScore"});
        JSONArray jsonArray = JSONArray.fromObject(masterList, config);
        return jsonArray;
    }

    @Override
    public Master findOne(Integer masterId) {
        return masterRepository.findOne(masterId);
    }

    @Transactional
    @Override
    public String addMaster(String userName, String password, String openId) {

        Master master = masterRepository.findByUserNameAndPassword(userName, password);
        if (master != null) {
            master.setOpenId(openId);
            masterRepository.save(master);
            return "suceess";
        } else {
            return "error";
        }
    }

    @Override
    public JSONObject sumMasterScore(String openId) {
        JSONObject jsonObject = new JSONObject();
        Double sum = 0.0;
        List<MasterScore> masterScoreList = masterScoreRepository.findAll(new Specification<MasterScore>() {
            @Override
            public Predicate toPredicate(Root<MasterScore> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();

                //专家openid
                Join<MasterScore, Answer> join = root.join("masterScoreAnswer");
                Join<Join, Master> join1 = join.join("master");
                Predicate p = criteriaBuilder.equal(join1.get("openId").as(String.class), openId);
                predicateList.add(p);


                Predicate predicate = criteriaBuilder.equal(root.get("status").as(String.class), "未提现");
                predicateList.add(predicate);


                criteriaQuery.where(predicateList.toArray(new Predicate[predicateList.size()]));
                return null;
            }
        });
        for (MasterScore masterScore : masterScoreList) {
            sum = masterScore.getNum() + sum;
        }
        jsonObject.put("monthScore", sum);
        //总积分
        Double sum1 = 0.0;
        List<MasterScore> masterScoreList1 = masterScoreRepository.findAll(new Specification<MasterScore>() {
            @Override
            public Predicate toPredicate(Root<MasterScore> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();

                //专家openid
                Join<MasterScore, Answer> join = root.join("masterScoreAnswer");
                Join<Join, Master> join1 = join.join("master");
                Predicate p = criteriaBuilder.equal(join1.get("openId").as(String.class), openId);
                predicateList.add(p);
                criteriaQuery.where(predicateList.toArray(new Predicate[predicateList.size()]));
                return null;
            }
        });
        System.out.println(masterScoreList1.size() + "***************");
        for (MasterScore masterScore : masterScoreList1) {
            sum1 = masterScore.getNum() + sum1;
        }
        jsonObject.put("sumScore", sum1);
        return jsonObject;
    }


    @Override
    public void updateMasterInfo(String wxNum, String headImg, String info, String password, String name, String goodAt) {
        Master master = masterRepository.findByOpenId(wxNum);
        if (headImg != null && !headImg.equals("")) {

            headImg = headImg.replace("wxfile:", "https://");
            headImg = headImg.substring(0, 8) + "qny.liuxuanlong.xyz/" + headImg.substring(8);
            master.setHeadImg(headImg);
        }

        master.setInfo(info);
        master.setPassword(password);
        master.setName(name);
        master.setGoodAt(goodAt);
        masterRepository.save(master);
        SysUser sysUser = sysUserRepository.findByUserName(master.getUserName());
        sysUser.setPassword(password);
        sysUserRepository.save(sysUser);
    }

    @Override
    public JSONObject findMasterInfo(String wxNum) {
        Master master = masterRepository.findByOpenId(wxNum);
        JsonConfig config = new JsonConfig();
        config.setExcludes(new String[]{"hospitalPermissionSet", "master", "hospitalImgSet", "hospitalFieldList", "userSet", "masterList", "answer", "praiseUserSet", "answerList", "question", "masterScoreAnswer", "answerImgSet"});
        JSONObject jsonObject = JSONObject.fromObject(master, config);
        return jsonObject;
    }

    @Override
    public String checkMasterIsBlack(String wxNum) {
        Master master = masterRepository.findByOpenId(wxNum);
        if (master.getIsBlack() != null && "是".equals(master.getIsBlack())) {
            return "yes";
        } else {
            return "no";
        }

    }


}
